package com.gitee.wsl.result.tran

import com.gitee.wsl.result.EntryResult
import com.gitee.wsl.result.sample.ValueResult

/**
 * Accumulates value starting with [initial] value and applying [operation] from right to left to
 * each element and current accumulator value.
 */
inline fun <T, R, E> List<T>.foldRight(initial: R, operation: (T, acc: R) -> EntryResult<R, E>): EntryResult<R, E> {
    var accumulator = initial

    if (isNotEmpty()) {
        val iterator = listIterator(size)
        while (iterator.hasPrevious()) {
            val result = operation(iterator.previous(), accumulator)
            accumulator = when {
                result.isOk -> result.value
                //is ResultEntry.Loading -> result.value!!
                else -> return ValueResult.Err(result.error)
            }
        }
    }

    return ValueResult.Ok(accumulator)
}
